package com.meiyuetao.myt.chinababy.service;

import java.util.List;

import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.service.BaseService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.meiyuetao.myt.chinababy.dao.CbLotteryWinDao;
import com.meiyuetao.myt.chinababy.entity.CbLotteryWin;
import com.meiyuetao.myt.chinababy.entity.CbLotteryWin.WinStatusEnum;
import com.meiyuetao.myt.purchase.entity.Supplier;
import com.meiyuetao.myt.purchase.service.SupplierService;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;

@Service
@Transactional
public class CbLotteryWinService extends BaseService<CbLotteryWin, Long> {

    @Autowired
    private CbLotteryWinDao cbLotteryWinDao;
    @Autowired
    private SupplierService supplierService;

    @Override
    protected BaseDao<CbLotteryWin, Long> getEntityDao() {
        return cbLotteryWinDao;
    }

    public Integer updateDelivery(List<CbLotteryWin> cbLotteryWins) {
        int i = 0;
        if (CollectionUtils.isEmpty(cbLotteryWins)) {
            cbLotteryWins = cbLotteryWinDao.findRelateBoxOrder();
        }
        for (CbLotteryWin item : cbLotteryWins) {
            BoxOrder boxOrder = item.getBoxOrder();
            if (boxOrder != null) {
                BoxOrderDetail boxOrderDetail = boxOrder.getBoxOrderDetails().get(0);
                if (StringUtils.isNotBlank(boxOrderDetail.getLogisticsName()) && StringUtils.isNotBlank(boxOrderDetail.getLogisticsNo())) {
                    Supplier logistics = supplierService.findByProperty("abbr", boxOrderDetail.getLogisticsName().trim());
                    if (logistics == null) {
                        logistics = supplierService.findByProperty("alias", boxOrderDetail.getLogisticsName().trim());
                    }
                    item.setLogisticsNo(boxOrderDetail.getLogisticsNo());
                    item.setLogistics(logistics);
                    item.setWinStatus(WinStatusEnum.SENT);
                    cbLotteryWinDao.save(item);
                    i++;
                }
            }
        }
        return i;
    }
}
